package com.wxq.yaoxia;


import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import com.wxq.net.NetClient;
import com.wxq.net.NetWorkThread;
import com.wxq.yaoxia.mainborad.YXMainboradActivity;
import com.wxq.yaoxia.util.SharedPreferencesUtil;
import com.wxq.yaoxia.util.YXConstants;
import com.wxq.yaoxia.util.YXUtility;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class YXUpdateActivity extends YXBaseNetActivity {

	Handler mHandler = new Handler();
	Button updateButton;
	String updataUrlStr;
	int localVersion ;
	static String VERSION = "version";
	ProgressDialog mProgressDialog;
	ProgressBar waitBar;
	ProgressBar subWaitBar;
	TextView subwaitBarTV;
	TextView timeinfoTV;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentViewWithTopbar(R.layout.yx_update, R.layout.yx_topbar);
		waitBar = (ProgressBar) findViewById(R.id.waitBar);
		subWaitBar = (ProgressBar) findViewById(R.id.subwaitBar);
		subwaitBarTV = (TextView) findViewById(R.id.subwaitBarTV);
		timeinfoTV = (TextView) findViewById(R.id.timeinfoTV);
		
		// instantiate it within the onCreate method
				mProgressDialog = new ProgressDialog(this);
				mProgressDialog.setMessage("Updating file,please wait...");
				mProgressDialog.setIndeterminate(false);
				mProgressDialog.setMax(100);
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		
		subWaitBar.setVisibility(View.INVISIBLE);
		subwaitBarTV.setVisibility(View.INVISIBLE);
		
		updateButton = (Button) findViewById(R.id.updateBtn);
		updateButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//获得网络数据
				NetWorkThread netWorkThread = new NetWorkThread(YXUpdateActivity.this, YXUpdateActivity.this, mHandler);
				netWorkThread.start();
			}
		});
	}

	@Override
	public void setTopBarButtonListener() {
		Button leftBtn = (Button) findViewById(R.id.btnLeft);
    	Button rightBtnButton = (Button) findViewById(R.id.btnRight);
    	TextView centerTV = (TextView) findViewById(R.id.centerTV);
    	
    	leftBtn.setVisibility(View.VISIBLE);
    	leftBtn.setText("返回");
    	leftBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
    	rightBtnButton.setVisibility(View.VISIBLE);
//    	rightBtnButton.setText("药");
    	rightBtnButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(YXUpdateActivity.this, YXMainboradActivity.class);
				YXUpdateActivity.this.startActivity(intent);
			}
		});
    	centerTV.setVisibility(View.VISIBLE);
    	centerTV.setText("更新");
	}

	@Override
	public void getNetworkData() {
		
		String timestamp = Calendar.getInstance().getTime().getTime()+""; 
		
		String url = String.format(YXConstants.URL_UPDATE, timestamp);
		//Log.d("wxq", "url = "+url);
		String result = NetClient.doGet(url);
		Log.d("wxq", "result = "+result);
		if(TextUtils.isEmpty(result))
		{
			YXUtility.showToast(this, "Get data erro,please check your network!", mHandler);
			return ;
		}
		try {
			JSONObject resultJSON = new JSONObject(result);
			int code = resultJSON.getInt("code");
			String msg = resultJSON.getString("message");
			if(code == 500)
			{
				YXUtility.showToast(this, msg, mHandler);
			}
			else if(code == 200)
			{
				JSONObject dbinfoObject = resultJSON.getJSONArray("dbinfo").getJSONObject(0);
				int serverVersion = dbinfoObject.getInt("version");
				updataUrlStr = dbinfoObject.getString("dbUrl");
				//Log.d("wxq", "dbUrl ="+updataUrlStr);
				
				SharedPreferencesUtil spu = new SharedPreferencesUtil(this);
				String versionStr = spu.read(VERSION);	
				if(TextUtils.isEmpty(versionStr))
				{
					localVersion = 2;
				}
				else {
					localVersion = Integer.parseInt(versionStr);
				}
				
				Log.d("wxq", "version = "+localVersion);
				//localVersion = -1;
				if(localVersion < serverVersion)
				{
					//更新
					Log.d("wxq", "开始下载！");
					downloadDB();
					
					spu.save(VERSION, serverVersion+"");
				}
				else {
					Log.d("wxq", "无需更新。");
					mHandler.post(new Runnable() {
						
						@Override
						public void run() {
							timeinfoTV.setText("当前为最新版，无须更新");
						}
					});
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}	
	
	public void downloadDB() {
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				// execute this when the downloader must be fired
				DownloadFileTask downloadFile = new DownloadFileTask();
				downloadFile.execute(updataUrlStr);//updataUrlStr
			}
		});
		
	}

	
	    // usually, subclasses of AsyncTask are declared inside the activity class.
		// that way, you can easily modify the UI thread from here
		private class DownloadFileTask extends AsyncTask<String, Integer, String> {
		    @Override
		    protected String doInBackground(String... sUrl) {
		        try {
		            URL url = new URL(sUrl[0]);
		            URLConnection connection = url.openConnection();
		            connection.connect();
		            // this will be useful so that you can show a typical 0-100% progress bar
		            int fileLength = connection.getContentLength();

		            // download the file
		            InputStream input = new BufferedInputStream(url.openStream());
		            
		            YXUtility.CreateFile(YXConstants.DATABASE_TEMP_FULLPATH);
		            
		            OutputStream output = new FileOutputStream(YXConstants.DATABASE_TEMP_FULLPATH);

		            byte data[] = new byte[1024];
		            long total = 0;
		            int count;
		            while ((count = input.read(data)) != -1) {
		                total += count;
		                // publishing the progress....
		                publishProgress((int) (total * 100 / fileLength));
		                output.write(data, 0, count);
		            }

		            output.flush();
		            output.close();
		            input.close();
		        } catch (Exception e) {
		        	e.printStackTrace();
		        }
		        
		        try {
					YXUtility.copyFile(YXConstants.DATABASE_TEMP_FULLPATH, YXConstants.DATABASE_PATH+YXConstants.DATABASE_NAME);
				} catch (Exception e) {
					e.printStackTrace();
				}
		        return null;
		    }
		    
		    @Override
		    protected void onPreExecute() {
		        super.onPreExecute();
		        mProgressDialog.show();
		        waitBar.setProgress(0);
		        subWaitBar.setVisibility(View.VISIBLE);
		        subwaitBarTV.setVisibility(View.VISIBLE);
		    }

		    @Override
		    protected void onProgressUpdate(Integer... progress) {
		        super.onProgressUpdate(progress);
		        mProgressDialog.setProgress(progress[0]);
		        waitBar.setProgress(progress[0]);
		    }

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				mProgressDialog.dismiss();
				waitBar.setProgress(0);
				subWaitBar.setVisibility(View.INVISIBLE);
		        subwaitBarTV.setVisibility(View.INVISIBLE);
		        timeinfoTV.setText("已更新："+ DateFormat.format("yyyy-MM-dd kk:mm:ss",Calendar.getInstance().getTime()).toString());
			}
		}
}
